<?php
namespace Admin\Controller;

use Think\Controller;

class LoginController extends Controller{
    //展示登录界面
    public function index(){
        $this -> display();
    }
    //处理登录
    public function dologin(){
        //初始化返回的值
        $arr = ['status' => 1,'msg' => '登录失败！','data'=>''];
        if(IS_AJAX){
            //用I函数接受前台传过来的值
            $userName = I('post.username/s','');
            $password = I('post.password/s','','strip_tags');
            $password = _md5($password);
            //判断用户名是否为空
            if(!isset($userName)){
                $arr['msg'] = '用户名不能为空！';
                exit(json_encode($arr));
            }
            //判断用户名是否合法
            $rule = preg_match('/^[A-Za-z0-9]+$/',$userName);
            if($rule < 1){
                $arr['msg'] = '用户名不合法！';
                exit(json_encode($arr));
            }
            //判断密码是否为空
            if(!isset($password)){
                $arr['msg'] = '密码不能为空！';
                exit(json_encode($arr));
            }
            $admin = M('admin');
            $map['username'] = $userName;
            $data = $admin -> where($map)->find();
            if(empty($data)){
                $arr['msg'] = '该用户不存在！';
                exit(json_encode($arr));
            }
            if($data['status'] == 1){
                if($password == $data['password']){
                    $map['loginNum'] = $data['loginnum'] + 1;
                    $map['loginTime'] = time();
                    $map['ip'] = get_client_ip();
                    $userid['id']  = $data['id'];
                    $admin -> where($userid) -> save($map);
                    //$admin -> query('update dx_admin set loginNum=' . $data['loginnum'] . '+1 WHERE id=' .$data['id'] );
                    $arr['status'] = 0;
                    $arr['msg'] = '登录成功';
                    $_SESSION['user']=array(
                        'id'=>$data['id'],
                        'username'=>$data['username']
                    );
                }else{
                    $arr['msg'] = '密码错误！';
                }
            }else{
                $arr['msg'] = '该用户被禁用！请向超级管理员申诉~';
            }
        }
        echo json_encode($arr);
    }
    public function logout(){
        session('user',null);
        $this->redirect('Admin/Login/index');
    }
}
